package uk.co.agileworks.bidpirate.web;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import uk.co.agileworks.bidpirate.model.User;
import uk.co.agileworks.bidpirate.service.ServiceException;

@Controller
public class AccountForm extends BaseController {

	public static final String FORM = "account";
	public static final String SUCCESS = "redirect:/listBids.html";

	@Resource
	private Validator<User> userValidator;

	@RequestMapping(value = "/account-create.html", method = RequestMethod.POST)
	public String createAccount(@ModelAttribute("user") User user, Errors errors) {

		if (userValidator.validate(user, errors)) {
			try {
				businessFacade.createAccount(user);
			} catch (ServiceException e) {
				errors.reject(e.getMessage());
			}
		}
		return errors.hasErrors() ? FORM : SUCCESS;
	}

	@RequestMapping(value = "/account.html", method = RequestMethod.GET)
	public void getAccount(Model model) {
		model.addAttribute(userSession.getUser());
	}

	@RequestMapping(value = "/account-logIn.html", method = RequestMethod.POST)
	public String logIn(@ModelAttribute("user") User user, Errors errors) {

		if (userValidator.validate(user, errors)) {
			try {
				businessFacade.logIn(user);
			} catch (ServiceException e) {
				errors.reject(e.getMessage());
			}
		}
		return errors.hasErrors() ? FORM : SUCCESS;
	}

	@RequestMapping(value = "/account-logOut.html", method = RequestMethod.GET)
	public String logOut(Model model) {
		
		userSession.logOut();
		model.addAttribute(userSession.getUser());
		return FORM;
	}

	@RequestMapping(value = "/account-update.html", method = RequestMethod.POST)
	public String updateAccount(@ModelAttribute("user") User user, Errors errors) {

		if (userValidator.validate(user, errors)) {
			businessFacade.updateAccount(user);
		}
		return errors.hasErrors() ? FORM : SUCCESS;
	}

}
